import { Fragment, createElement } from "react";
import { Modal, message } from 'antd';
import type { ModalStaticFunctions } from "antd/es/modal/confirm";
import type { MessageInstance } from "antd/es/message/interface";

class Prompt {
  private modal: Omit<ModalStaticFunctions, "warn">;
  private messageApi: MessageInstance;

  constructor() {
    message.config({
      duration: 2
    });
  }

  /**
   * 初始化挂载点
   */
  initMountPoint = () => {
    const [modal, modalContextHolder] = Modal.useModal();
    const [messageApi, messageContextHolder] = message.useMessage();
    this.modal = modal;
    this.messageApi = messageApi;
    return createElement(Fragment, {
      children: [
        createElement(Fragment, { key: "1", children: modalContextHolder }),
        createElement(Fragment, { key: "2", children: messageContextHolder }),
      ]
    })
  }

  /**
   * 消息
   * @param {String} msg
   * @param {Number} duration
   * @param {Function} onClose
   */
  info(msg: string, duration = 2, onClose = () => { }) {
    this.messageApi.info(msg, duration, onClose);
  }

  /**
   * 提示成功
   * @param {String} msg
   * @param {Number} duration
   * @param {Function} onClose
   */
  success(msg: string, duration = 2, onClose = () => { }) {
    this.messageApi.success(msg, duration, onClose);
  }

  /**
   * 提示错误
   * @param {String | Array} msg
   * @param {Number} duration
   * @param {Function} onClose
   */
  error(msg: string, duration = 2, onClose = () => { }) {
    if (Array.isArray(msg)) {
      let newMsg = "";
      msg.forEach(item => newMsg += `${item.message}\n`);
      msg = newMsg;
    }

    this.messageApi.error(msg, duration, onClose);
  }

  /**
   * 提示警告
   * @param {String} msg
   * @param {Number} duration
   * @param {Function} onClose
   */
  warn(msg: string, duration = 2, onClose = () => { }) {
    this.messageApi.warning(msg, duration, onClose);
  }

  /**
   * 确认提示框
   * @param {Function} cbForOk return Promise对象
   * @param {Object} options
   */
  confirm<T = any>(cbForOk: () => Promise<T>, options = {}) {
    options = Object.assign({
      title: '确定删除吗？',
      // content: <h1>When clicked the OK button, this dialog will be closed after 1 second</h1>,
      content: '',    // content可以是react节点实例
      okText: '确定',
      cancelText: '取消',
      onOk() {
        const ok = cbForOk();
        if (!(ok instanceof Promise)) {
          throw new Error("confirm onOk回调方法返回的不是Promise对象");
        }
        ok.catch(e => console.error(e));
        return ok;
      },
      onCancel() {
        return null;
      },
    }, options);


    return this.modal.confirm(options);
  }

}

export default new Prompt();
